package com.baidu.unlockdemo.lifecyle

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.baidu.unlockdemo.R
import com.baidu.unlockdemo.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    lateinit var binding: ActivityMainBinding

    //使用代理创建ViewModel的对象
    val mViewModel: MainViewModel by viewModels()

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        //希望能够感知mainViewModel里面的number属性在变化
        //所以number属性应该能够被观察
        // LiveData
        // MutableLiveData
        /*
        mViewModel.number.observe(this, object : Observer<Int> {
            override fun onChanged(value: Int) {
                binding.tvResult.text = "$value"
            }
        })

        mViewModel.number.observe(this) { value ->
            binding.tvResult.text = "$value"
        }
        */

        /*
        view: XML
        ui和数据的中转站 ： Activity
        数据：ViewModel

        DataBinding
        view  -  viewModel

        xml监听数据 "@{viewModel.number}"

         */

        //在Activity中建立 xml和 viewModel的关联
        //xml中要什么数据，就给他什么数据
        binding.viewModel = mViewModel
        binding.eventListener = EventListener()
        //设置binding类的生命周期的拥有者是这个Activity
        binding.lifecycleOwner = this
        //告诉binding，数据已经准备好了 立刻刷新
        binding.executePendingBindings()

//        binding.button.setOnClickListener {
//            mViewModel.addOne()
//        }

        //配置MusicPlayer观察的对象
        //lifecycle.addObserver(mViewModel.mediaPlayer)

        /**
         * Activity: 分发生命周期的状态
         *   lifecycle.addObserver(观察者)
         * MainViewModel： 监听Activity的生命周期
         *      持有MusicPLayer的对象
         * MusicPlayer: 用来观察Activity的生命周期 做出不同的事件处理
         */
    }

    //当前的Activity被系统杀死时，会调用onSaveInstanceState方法
//    override fun onSaveInstanceState(outState: Bundle) {
//        //将自己需要的数据保存起来
//        outState.putInt("result", num)
//        super.onSaveInstanceState(outState)
//    }


}















